/*
* @Description: 快捷键工具函数
* @Author: heyang
* @EditTime: 2023-12-07 16:04:39
* @LastEditors:  heyang
* @LastEditTime: 2023-12-07 16:04:39
*/

let hotKeys = {};
let originalHotKeys = {}; // 保存原始的快捷键状态: 类似于弹窗关闭需要缓存页面或者上一层的快捷键
export class HotKeyDto {
  key: string;
  callback: Function;
  isPassword?: boolean;
  buttonName?: string;
}

/*
* @Description: 创建快捷键 批量
* @param: event
* @Date: 2023-12-05 14:30:38
*/
export function registerHotKeys(shortcutsMap: HotKeyDto[], isModal: boolean = false) {
  if (isModal) {
    recordOriginalHotKeys();
  }
  shortcutsMap.forEach(value => {
    if (!hotKeys[value.key]) {
      hotKeys[value.key] = new Set();
    }
    // 快捷键禁用逻辑
    hotKeys[value.key].add(() => {
      if (value.isPassword) {
        document.getElementById(`hotKey-${value.buttonName}`).click();
      } else {
        value.callback();
      }
    });
  })
}

/*
* @Description: 注销快捷键 批量
* @param: isModal: 是否是弹窗 shortcutsMap: 自定义注销已注册的hotKey
* @Date: 2023-12-05 14:30:38
*/
export function unregisterHotKeys(isModal: boolean = false, shortcutsMap?: HotKeyDto[]) {
  if (shortcutsMap?.length) {
    shortcutsMap.forEach(value => {
      if (hotKeys[value.key]) {
        hotKeys[value.key].clear();
        if (hotKeys[value.key].size === 0) {
          delete hotKeys[value.key];
        }
      }
    });
  } else {
    hotKeys = new Object();
  }
  if (isModal) {
    restoreOriginalHotKeys();
  }
}

/*
* @Description: 记录上层页面快捷键 不切换路由的，弹窗形式
* @Date: 2023-12-05 14:30:38
*/
function recordOriginalHotKeys() {
  // 保存上层快捷键
  Object.keys(hotKeys).forEach(key => {
    originalHotKeys[key] = new Set(Array.from(hotKeys[key]));
  });
  // 清空当前快捷键
  hotKeys = new Object();
}

/*
* @Description: 恢复上层页面快捷键
* @Date: 2023-12-05 14:30:38
*/
function restoreOriginalHotKeys() {
  // 清空当前快捷键
  hotKeys = new Object();
  // 恢复
  Object.keys(originalHotKeys).forEach(key => {
    hotKeys[key] = new Set(Array.from(originalHotKeys[key]));
  });
}

/*
* @Description: 快捷键触发函数
* @param: event 键盘事件
* @Date: 2023-12-05 14:30:38
*/
export function handleKeyPress(event) {
  const key = event.key.toLowerCase();
  // 如果同时按下了 Ctrl 键（在 macOS 上可能是 Command 键）
  if ((event.ctrlKey || event.metaKey) && hotKeys[`ctrl+${key}`]) {
    event.preventDefault(); // 阻止浏览器默认行为
    hotKeys[`ctrl+${key}`].forEach(callback => callback());
  } else if (hotKeys[key]) {
    event.preventDefault(); // 阻止浏览器默认行为
    hotKeys[key].forEach(callback => callback());
  }

}